import React ,{Component} from 'react';
import { ImagePicker } from 'antd-mobile';
import axios from 'axios'
import COS from 'cos-js-sdk-v5'

const instance = axios.create();
const data = [];
var Bucket = 'ceoja-1251886366';
var Region = 'ap-guangzhou';
var getAuthorization = function (options, callback) {
  var authorization = COS.getAuthorization({
      SecretId: 'AKIDJWpyvgTrKb5RbZMvJ2d6NWUFoBMLwhig',
      SecretKey: '2vdBXgeQ4Wr480gASZUHEWjkZCdsxkNF',
      Method: options.Method,
      Key: options.Key,
  });
  callback(authorization);
};

export default class ImagePickerExamples extends Component {
  constructor(props) {
    super(props);

    let files = props.files || [];
    if (!Array.isArray(files)) {
        files = [files];
    }

    this.initFiles = files;
    this.cos = {}

    this.state = {
      token: false,
      cdn: "http://ceoja-1251886366.cos.ap-guangzhou.myqcloud.com/",
      pending: false,
      files: this.initFiles,
    };

    this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    this.cos = new COS({
      // 必选参数
      getAuthorization: getAuthorization,
      // 可选参数
      FileParallelLimit: 3,    // 控制文件上传并发数
      ChunkParallelLimit: 3,   // 控制单个文件下分片上传并发数
      ChunkSize: 1024 * 1024,  // 控制分片大小，单位 B
      ProgressInterval: 1000,  // 控制 onProgress 回调的间隔
    });
    console.log(this.cos)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.files!=this.props.files) {
      this.setState({files: nextProps.files})
    }
  }

  putImage = (files, _name, formData) => {
    axios.put(`http://ceoja-1251886366.cos.ap-guangzhou.myqcloud.com/${_name}`, 
    formData, {
      headers: {
        Authorization: this.state.token
      }
    }
    ).then(resp=>{
      console.log(resp)
      files.push({
          url: cdn + _name + "?imageView2/2/h/80/w/80"})

      this.setState({
          token: token,
          cdn: cdn,
          files: files,
          pending: false,
      });
      this.props.callback(files,type,index)
  }).catch(err=>console.log(err))
  }

  uploadImage = (files, _name, formData) => {
    instance.get(`/api/getTXAuthorization?method=put&pathname=${encodeURIComponent(_name)}`)
    .then(resp => {
      console.log(resp.data)
      this.setState({
        token: resp.data,
        pending: false,
        files: this.initFiles || [],
      })
    }).then(() => {
      this.putImage(files, _name, formData)
    })
  
  }

  onChange(items, type, index) {
      console.log(items, type, index);
      if (type == 'remove' ) {
         this.setState(Object.assign({}, this.state, {files: items}));
         this.props.callback(items,type,index)
       } else if (type == 'add') {
          let formData, token = this.state.token, cdn = this.state.cdn;
          items.filter(x => x.file).forEach((file) => {
            formData = new FormData();
            formData.append('file', file.file);

            // 复制一份
            let files = this.state.files.slice(),
              _name =  '/'+new Date().getTime() +'/' + file.file.name

            console.log(Bucket,Region,file)

            if (!file.file) return;

            this.cos.sliceUploadFile({
                Bucket: Bucket,
                Region: Region,
                Key: _name,
                Body: file.file,
            }, (err, data) => {
                console.log(err, data, file.file.type);
                // url 会决定缩略图
                let url = file.file.type.startsWith('image/')?'//'+data.Location+'?imageView2/2/w/84/h/84' : 
                  '//ceoja-1251886366.cos.ap-guangzhou.myqcloud.com/1519283316172file-placeholder.png'
                files.push({url: url, uri: '//'+data.Location}) 
                this.setState({files})
                this.props.callback(files,type,index)
            });

            // this.uploadImage(files, _name, formData)
        });
      }
  }
  
 
  render() {
    const { files } = this.state;
    return (
        <ImagePicker
          files={files}
          onChange={this.onChange}
          onImageClick={(index, fs) => console.log(index, fs)}
          selectable={files.length < 10}
          accept="image/*,.doc, .docx,.txt,.pdf"
        />
    );
  }
}
